package com.ruike.alisurface.Serials.outGoods;

import com.ruike.alisurface.Serials.MsgEventBus;
import com.ruike.alisurface.Serials.Ttys3Utils;
import com.voodoo.lib_utils.L;

import org.greenrobot.eventbus.EventBus;

import java.util.Timer;
import java.util.TimerTask;

/**
 * 点击转动出货类
 */
public class ShopChUtils {

   public static volatile boolean putflag; //是否停止延迟，开始下一次出货
    static Timer timer;//倒计时

    public static void setPutflag(boolean putflag) {
        ShopChUtils.putflag = putflag;
    }

    /**
     * 类型及货道号
     *
     * @param type
     * @param slotindex
     */
    public static void shopTodo(int type, int slotindex) {
        if (type == 21001) {  //弹簧货到
            setgetShop(slotindex, "0");
        } else if (type == 21002) {//蛇形货道
            setgetShop(slotindex, "2");
        } else if (type == 21003) {//电磁锁
            setgetShop(slotindex, "1");
        } else {
            L.i("--货道类型异常- ", slotindex);
        }
    }

    /**
     * 循环 多次出货
     *
     * @param number
     * @param index
     * @param indextype
     */
    public static void setgetShop(int number, int index, int indextype) {
        L.i("----index:", index, "-----number:", number, "-----type:", indextype);
        for (int i = 0; i < number; i++) {
            shopTodo(indextype, index);
        }
    }


    /**
     * 出货及延迟
     *
     * @param slotindex
     * @param type
     */
    public static void setgetShop(int slotindex, String type) {
        try {
            Thread.sleep(300);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Ttys3Utils.getInstance().Qudong(1, slotindex - 1, type);
        putflag = true;

        timer = new Timer();

        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                L.i("出货倒计时完成   取消计时，开始下一次出货");
                putflag = false;
                if (timer != null) {
                    timer.cancel();
                    timer = null;
                    EventBus.getDefault().post(new MsgEventBus("出货倒计时完成", "出货计时到9秒 ，结束计时@" + (slotindex - 1)));
                    return;
                }
            }
        };
        timer.schedule(timerTask, 13000);
        while (putflag) {
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        if (timer != null) {
            L.i("出货倒计时 未完成   主动取消计时，开始下一次出货");
            EventBus.getDefault().post(new MsgEventBus("出货倒计时未完成", "出货未到计时9秒 ，结束计时"));
            timer.cancel();
            timer = null;
        }
    }
}
